//
//  HMHomeViewModel.swift
//  Weibo
//
//  Created by Apple on 2017/7/13.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import SDWebImage

//  封装首页的网络请求
class HMHomeViewModel: NSObject {

    //  微博数据源
    lazy var statusList: [HMStatusViewModel] = [HMStatusViewModel]()
    //  加载微博数据
    func loadData(isUp: Bool, callBack: @escaping (Bool, String)->()) {
        let token = HMUserAccountViewModel.sharedUserAccount.accessToken!
        //  上拉加载默认id
        var max_id: Int64 = 0
        var since_id: Int64 = 0
        if isUp {
            max_id = statusList.last?.status?.id ?? 0
            if max_id > 0 {
                max_id -= 1
            }
        } else {
            since_id = statusList.first?.status?.id ?? 0
        }
        
        var message: String = "没有加载到最新的微博"
        
        //  判断本地是否有缓存数据
        let localDicArray = HMStatusDAL.checkCacheData(maxId: max_id, sinceId: since_id)
        if localDicArray.count > 0 {
            //  本地有缓存数据
            let modelArray = NSArray.yy_modelArray(with: HMStatus.self, json: localDicArray) as! [HMStatus]
            var tempArray = [HMStatusViewModel]()
           
            //  遍历模型数组转出ViewModel数组
            for model in modelArray {
                let viewModel = HMStatusViewModel()
                //  关联模型
                viewModel.status = model
                tempArray.append(viewModel)
            }
            
            //  记录微博数据
            //            self.statusList = tempArray
            if isUp {
                self.statusList.append(contentsOf: tempArray)
            } else {
                self.statusList.insert(contentsOf: tempArray, at: 0)
            }
            if tempArray.count > 0 {
                message = "加载了\(tempArray.count)条微博"
            }
            //  重新加载数据
            callBack(true, message)
            
            return
        }
        
        //  本地没有数据加载网络微博数据
        HMNetworkTools.sharedTools.requestStatuses(accessToken: token, max_id: max_id, since_id: since_id) { (response, error) in
            if error != nil {
                print("error: \(error!)")
                callBack(false, message)
                return
            }
            
            let dic = response as! [String: Any]
            //  获取微博字典数组
            let statusDicArray = dic["statuses"] as! [[String: Any]]
            //  缓存微博数据
            HMStatusDAL.cacheData(statusDicArray: statusDicArray)
            //  字典转模型，使用YYModel
            let modelArray = NSArray.yy_modelArray(with: HMStatus.self, json: statusDicArray) as! [HMStatus]
            var tempArray = [HMStatusViewModel]()
            //  创建调度组
            let group = DispatchGroup()
            //  遍历模型数组转出ViewModel数组
            for model in modelArray {
                let viewModel = HMStatusViewModel()
                //  关联模型
                viewModel.status = model
                tempArray.append(viewModel)
                
                //  下载配图个数等于1的图片
                if model.pic_urls?.count == 1 {
                    group.enter()
                    //  原创微博配图下载
                    if let imageUrl = model.pic_urls?.first?.thumbnail_pic {
                        SDWebImageManager.shared().loadImage(with: URL(string: imageUrl), options: [], progress: nil, completed: { (image, imageData, error, _, _, _) in
                            print("原创微博单张图片下载完成")
                            group.leave()
                        })
                    }
                }
                if model.retweeted_status?.pic_urls?.count == 1 {
                    //  转发微博配图下载
                    group.enter()
                    if let imageUrl = model.retweeted_status?.pic_urls?.first?.thumbnail_pic {
                        SDWebImageManager.shared().loadImage(with: URL(string: imageUrl), options: [], progress: nil, completed: { (image, imageData, error, _, _, _) in
                            print("转发微博单张图片下载完成")
                            group.leave()
                        })
                    }
                }
            }
            
            //  记录微博数据
//            self.statusList = tempArray
            if isUp {
                self.statusList.append(contentsOf: tempArray)
            } else {
                self.statusList.insert(contentsOf: tempArray, at: 0)
            }
            if tempArray.count > 0 {
                message = "加载了\(tempArray.count)条微博"
            }
            group.notify(queue: DispatchQueue.main, execute: {
                print("所有的单张图片都下载完成")
                //  重新加载数据
                callBack(true, message)
            })
            
        }
    }
    
}
